import _ from 'lodash';
function isValidDate(dateString) {
  const date = new Date(dateString);
  return date instanceof Date && !isNaN(date);
}
export function convertExp(farr,DataType,Condition) {
  if(farr&&farr[3]){
    DataType = farr[3]
  }

  if(farr&&farr[3]){
    Condition=farr[1]
    }
    if(farr&&farr.length==3){
      DataType = farr[1]
      Condition=farr[2]
    }
  farr.forEach((f, i) => {
    if (!f) {
      return;
    }
    try {
      f = JSON.parse(f);
    } catch (error) {}
    let cv = f.value || f.Value || f;

    if (typeof cv == 'string' && cv.includes('@')) {
      let ccv = Funcs.AtVarTransform(cv);
      if (typeof ccv == 'object') {
        ccv = Object.keys(ccv)
          .map(k => {
            // return `'${ccv[k]}'`
            return ccv[k];
          })
          .filter(ccvf => ccvf)
          .join();

           farr[1] = farr[1] == '=' ? 'in' : farr[1] == '<>' ? 'notin' : farr[1];
      }
      if (DataType== 'DateTime' || DataType == 'datetime'||DataType == 'Timestamp') {
        if(Condition=='='||Condition=='<>'){
          farr[i] =ccv.split(' ')[0]
        }else if(Condition=='>'){
          farr[i] = Funcs.AddSeconds(ccv.split(' ')[0]+ ' 23:59:59',1).replace(/\//ig,'-')
        }else if(Condition=='>='){
          farr[i] = (ccv.split(' ')[0]+ ' 00:00:00').replace(/\//ig,'-')
        }else if(Condition=='<'){
          farr[i] = (ccv.split(' ')[0]+ ' 00:00:00').replace(/\//ig,'-')
        }else if(Condition=='<='){
          farr[i] = Funcs.AddSeconds(ccv.split(' ')[0]+ ' 23:59:59',1).replace(/\//ig,'-')
        }else{
          if(i==0){
            farr[i] = Funcs.AddSeconds( ccv.split(' ')[0]+ ' 00:00:00',0).replace(/\//ig,'-')
          }else if(i==1){
            farr[i] = Funcs.AddSeconds(ccv.split(' ')[0]+ ' 23:59:59',1).replace(/\//ig,'-')
          }else{
            farr[i] = Funcs.AddSeconds( ccv.split(' ')[0]+ ' 00:00:00',0).replace(/\//ig,'-')
          }

        }
        // try {
        //   if(
        //     ccv&&ccv.split(' ')[1]=='23:59:59'&&farr&&farr.length==2
        //   ){
        //     farr[i] = Funcs.AddSeconds(ccv,1).replace(/\//ig,'-')
        //   }else{
        //     farr[i] = ccv;
        //   }
        // } catch (error) {
        //   farr[i] = ccv;
        // }
      } else {
          farr[i] = ccv //Funcs.AddSeconds( ccv.split(' ')[0]+ ' 00:00:00',0).replace(/\//ig,'-').split(' ')[0]
      }

    } else if (f && f.push) {
      convertExp(f,DataType,Condition);
    }
  });
}

export function FilterExpression(expression, conditionalColumn) {
  if (conditionalColumn) {
    let dataTypeMapping = {
      String: 'string',
      string: 'string',
      varchar: 'string',
      Varchar: 'string',
      Int: 'number',
      int: 'number',
      Long: 'number',
      long: 'number',
      Decimal: 'number',
      decimal: 'number',
      Number: 'number',
      number: 'number',
      boolean: 'boolean',
      Boolean: 'boolean',
      Time: 'datetime',
      time: 'datetime',
      Date: 'datetime',
      date: 'datetime',
      DateTime: 'datetime',
      datetime: 'datetime',
      Timestamp: 'datetime',
      timestamp: 'datetime',
    };
    conditionalColumn = conditionalColumn.map(field => {
      let filterField = {
        ...field,
        caption: field.fieldName, //`${field.tableName}.${field.fieldName}`,
        dataField: `${field.tableAlias}.${field.fieldCode}`,
        dataType: _.get(dataTypeMapping, field.dataType, 'string'),
        dataTypeOriginal: field.dataType,
      };
      return filterField;
    });
  }
  let vj = [];

  vj = toValueJson(JSON.parse(JSON.stringify(expression)), conditionalColumn);
  if (vj && vj.push) {
    convertExp(vj);
  }
  let val = uiFilter2FilterGroupWarp(vj, conditionalColumn);

  return JSON.stringify(val);
}
export function uiFilter2FilterGroupWarp(valueJson, fields) {
  if (
    _.size(valueJson) === 3 &&
    false == _.includes(valueJson, 'and') &&
    false == _.includes(valueJson, 'or')
  ) {
    valueJson = [valueJson];
  }
  return uiFilter2FilterGroup(valueJson, fields);
}
export function isCondition(criteria) {
  if (!Array.isArray(criteria)) {
    return false;
  }

  return (
    criteria.length > 1 &&
    !Array.isArray(criteria[0]) &&
    !Array.isArray(criteria[1])
  );
}
export function isGroup(criteria) {
  if (!Array.isArray(criteria)) {
    return false;
  }

  return (
    criteria.length < 2 ||
    Array.isArray(criteria[0]) ||
    Array.isArray(criteria[1])
  );
}
export function uiFilter2FilterGroup(filterArray, fields) {
  let Filters = _.transform(
    filterArray,
    (result, value) => {
      if (isCondition(value)) {
        let filter = _.zipObject(['Code', 'Condition', 'Value'], value);
        let fieldsConf = _.find(fields, { dataField: filter.Code });

        //if (!fieldsConf) {
        //   console.error(
        //     `请检查${filter.Code},在查询方案列信息未发现${filter.Code}列`,
        //   );
        //}

        filter.Name = _.get(fieldsConf, 'caption');
        filter.DataType = fieldsConf
          ? fieldsConf.dataTypeOriginal || fieldsConf.dataType
          : '';

        try {
          let valueObj = JSON.parse(filter.Value);
          filter.Value =
            filter.DataType == 'Boolean'
              ? valueObj.value == '是'
                ? 1
                : valueObj.value == '否'
                  ? 0
                  : valueObj.value
              : valueObj.value;
          filter.ValueName = filter.ValueName||(filter.Condition.trim() == 'between' ? '' : valueObj.name);
          filter.ValueType = valueObj.valueType;
        } catch (error) {}
        if (
          !filter.hasOwnProperty('ValueName') &&
          filter.Condition.trim() != 'between'
        ) {
          filter.ValueName = JSON.parse(JSON.stringify(filter)).Value;
          filter.ValueType = 0;
        }
        let item = { ElementType: 'Filter', ...filter };
        if (_.isDate(item.Value) || (typeof item.Value === 'string' && isValidDate(item.Value))) {
          //item.Value = formatDate(item.Value, fieldsConf.format);
          if(filter.DataType === "Date"){
            item.Value = item.Value.split(' ')[0];  // 只保留日期部分
          }
          item.ValueName = item.ValueName||item.Value;
        } else if (Array.isArray(item.Value)) {
          if(filter.Condition=='in'||filter.Condition=='notin'){
            if(Array.isArray(item.Value)){
              item.Value = item.Value.map(cvf=>cvf.value||cvf).filter(item=>item).join(',')||(item.ValueName&&item.ValueName.map&&item.ValueName.map(cvf=>cvf.value).filter(item=>item).join(','))
            }
            if(Array.isArray(item.ValueName)){
              item.ValueName = JSON.stringify(item.ValueName)
            }
          }else{
            _.each(item.Value, (val, i) => {
              if (_.isDate(val)|| (typeof val === 'string' && isValidDate(val))) {
               // item.Value[i] = formatDate(val, fieldsConf.format);

                if(filter.DataType=="Date"){
                  item.Value[i] =  item.Value[i].split(' ')[0]
                }

              }
            });
          }

        }
        result.push(item);
      } else if (isGroup(value)) {
        let group = uiFilter2FilterGroup(value, fields);
        result.push(group);
      } else {
        result.push({
          ElementType: 'Relation',
          Relation: value,
        });
      }
    },
    [],
  );

  let returnValue = {
    ElementType: 'Group',
    Filters: Filters,
  };

  return returnValue;
}

export function toValueJson(data, filed) {
  return Content2Obj(data, filed);
}
export function Content2Obj(item, fields, sorts) {
  if(!item) return
  let filterGroup = JSON.parse(item?.FilterContent || '{}');
  item.ValueJson = filterGroup2UiFilter(filterGroup.Filters, fields);
  return item.ValueJson;
}
export function filterGroup2UiFilter(filters, fields) {
  filters = filters || [];

  let returnValue = _.transform(
    filters,
    (result, value) => {
      switch (value.ElementType) {
        case 'Filter':
          if (value.Condition == 'between') {
            //value.ValueName = '';
            if(!(value.Value&&value.Value.join)){
              value.Value=''
            }
            if(value.Value&&value.Value.join('')==''){
              value.Value=''
            }
            if (value.ValueName && value.ValueName.includes('@')) {
              switch (value.ValueName) {
                case '@近30天':
                  value.ValueName = '@今天-29 - @今日末'.split(' - ');
                  break;
                case '@近半年':
                  value.ValueName = '@今天-179 - @今日末'.split(' - ');
                  break;
                default:
                  break;
              }
              value.Value = Funcs.AtVarTransform(value.ValueName)
            }

          } else {
            value.Value =
              value.Value || typeof value.Value == 'number'
                ? JSON.stringify({
                    value: value.Value,
                    name: value.hasOwnProperty('ValueName')
                      ? value.ValueName
                      : value.Value,
                    valueType: value.ValueType ? value.ValueType : 0,
                    DataType: value.DataType,
                  })
                : null;
          }

          result.push([value.Code, value.Condition, value.Value,value.DataType]);
          break;
        case 'Relation':
          result.push(value.Relation);
          break;
        case 'Group':
          result.push(filterGroup2UiFilter(value.Filters, fields));
          break;
      }
    },
    [],
  );
  return returnValue;
}
